/*
 * Copyright 2002-2006 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 */
package pikes.html.xhtml;

import java.util.Locale;

import pikes.xml.XMLTag;

public aspect I18NAspect {

    private I18NImpl I18N.i18nDelegate = new I18NImpl();
    
    public void I18N.setLang(Locale locale) {
        i18nDelegate.setLang(locale);
    }

    public void I18N.setDir(Direction dir) {
        i18nDelegate.setDir(dir);
    }
    
    public Locale I18N.getLang() {
        return i18nDelegate.getLang();
    }
    
    public Direction I18N.getDir() {
        return i18nDelegate.getDir();
    }
    
    pointcut decorateTag(I18N i18n) : execution( protected void TagFactory.decorateCreatedTag(..)) && this(i18n) && !within(I18NImpl);
    
    after(I18N i18n) : decorateTag(i18n) {
        XMLTag tag = (XMLTag)thisJoinPoint.getArgs()[0];
        
        i18n.i18nDelegate.decorateTag(tag);
        
    }
}

class I18NImpl  implements TagDecorator {

    private Language lang = null;

    private Direction dir = null;
    
    public void decorateTag(XMLTag tag) {
        if (lang != null) {
            lang.decorateTag(tag);
        }

        if (dir != null) {
            dir.decorateTag(tag);
        }
    }
    
    public void setLang(Locale locale) {
        if (locale == null) {
            this.lang = null;
        }
        else {
            this.lang = new Language(locale);
        }
    }

    public void setDir(Direction dir) {
        this.dir = dir;
    }
    
    public Locale getLang() {
        if (this.lang == null) {
            return null;
        }
        
        return lang.getLocale();
    }
    
    public Direction getDir() {
        return this.dir;
    }
}

class Language implements TagDecorator {

    private Locale locale = null;

    public Language(Locale locale) {
        super();
        this.locale = locale;
    }

    public void decorateTag(XMLTag tag) {
        tag.addAttribute("lang", locale.getLanguage());
    }

    public Locale getLocale() {
        return locale;
    }
}